package com.chengdu.third.controller.admin;


import com.chengdu.third.pojo.UserManger;
import com.chengdu.third.service.UserMangerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author jingbo:此模块负责后台登录
 * @create 2021--08--15  14:16
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserMangerService userService;

    //只有一个admin时候，登录后台
    @GetMapping()
    public String loginPage(){

        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        UserManger user = userService.checkUser(username, password);
        if(user != null){
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/admin";
        }
    }

    //    注销的方法:就后台登录后右上角的功能
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");  //只需要将user数据移除就行
        return "redirect:/admin";//重定向到登录页
    }



}
